<template>
    <div class="fieldManage zy-content ">

      <div class="searchBox search-box-layout">
        <Row :gutter="24">
          <Col span="4">
            <div>
              <p class="label">{{$t('common.company')}}</p>
              <div class="ipt">
                <Select v-model="searchParams.belongCompanyId"
                        filterable
                        clearable
                        @on-change="companySelectChange"
                        :placeholder="`${$t('common.selectInfo')}`">
                  <Option v-for="(item, index) of companyList"
                          :value="item.id"
                          :label="item.name"
                          :key="index">
                  </Option>
                </Select>
              </div>
            </div>
          </Col>
          <Col span="4">
            <div>
              <p class="label">{{$t('安装位置')}}</p>
              <div class="ipt">
                <Cascader
                    v-model="searchParams.org"
                    :data="orgList"
                    :transfer="true"
                    @on-change="handleCasChange"
                ></Cascader>
              </div>
            </div>
          </Col>
          <Col span="4">
            <div>
              <p class="label">{{$t('maintenance.EquipmentNo')}}</p>
              <div class="ipt">
                <Input
                    :placeholder="`${$t('common.inputInfo')}`"
                    clearable
                    type="text"
                    v-model="searchParams.deviceNo">
                </Input>
              </div>
            </div>
          </Col>
          <Col span="4">
            <div>
              <p class="label">{{$t('maintenance.EquipmentName')}}</p>
              <div class="ipt">
                <Input
                    :placeholder="`${$t('common.inputInfo')}`"
                    clearable
                    type="text"
                    v-model="searchParams.deviceName">
                </Input>
              </div>
            </div>
          </Col>
          <Col span="4">
            <div>
              <p class="label hide-label">--</p>
              <div class="ipt">
                <Button class="search-btn" type="primary" v-has="'ProductionIntervalSearch'" @click="changeNum()">
                    {{$t('common.Query')}}
                </Button>
                <Button
                    class="reset-btn"
                    @click="reset()"
                >{{ $t('common.reset') }}
                </Button>
              </div>
            </div>
          </Col>
        </Row>
      </div>

        <div class="list-layout mt16">
          <div class="btns clear">
            <span class="title">{{ $t('common.listInformation') }}</span>
            <Button @click="showAddModal" v-has="'ProductionIntervalSearch'">{{$t('common.New')}}</Button>
            <Button @click="importExcelShow" v-has="'ProductionIntervalImport'">{{$t('common.Import')}}</Button>
            <Button @click="exportTemplate" v-has="'ProductionIntervalTemplate'">{{$t('preliminary.DownloadTemplate')}}</Button>
            <Button @click="deleteAll" v-has="'ProductionIntervalDeletes'">{{ $t('common.batchDelete') }}</Button>
            <Button @click="exportTemplateClick" v-has="'ProductionIntervalExport'">{{$t('common.batchExport')}}</Button>
              <Button @click="getTableColumns(columns)">
                  {{ handleContextMenuStatus ? $t('显示操作栏') : $t('隐藏操作栏') }}
              </Button>
          </div>

          <div class="tableContent">
            <Table ellipsis ref="selection"  class="resizable-table" border @on-column-width-resize="onColumnWidthResize" :columns="columnsList" :data="tableData" @on-selection-change="onSelectChange">
              <template slot-scope="{ row }" slot="action">
                    <span class="operationBtn" v-has="'ProductionIntervalEdit'"
                          @click="showAddModal(row)"><i class="iconfont zy-common-bianji"></i>{{ $t('common.Edit') }}</span>
                <span class="operationBtn" v-has="'ProductionIntervalDelete'"
                      @click="(deleteModal = true), (deleteIds = [row.id])"><i class="iconfont zy-common-shanchu"></i>{{ $t('common.Delete') }}</span>
              </template>
            </Table>
          </div>

          <div class="pageWrap mt16">
            <pageLeftTitle :total="pageHelper.total" :selected="deleteIds.length" />
            <Page :total="pageHelper.total" :page-size="pageHelper.pageSize" :page-size-opts="$variable.pageSizes"
                  :current="pageHelper.pageNum"
                  @on-change="changePageNum" @on-page-size-change="changePageSize" show-sizer show-total/>
          </div>
        </div>
        <Modal :mask-closable="false" v-model="addModal" :title="addtitle" class="modal-content-layout">
            <Form
                ref="formValidate"
                class="formList"
                :model="formItem"
                :rules="getRules"
                label-position="top"
                 v-if="addModal"
            >
                <FormItem :label="$t('common.company')" prop="belongCompanyId">
                    <Select
                        v-model="formItem.belongCompanyId"
                        filterable
                        clearable
                        :placeholder="`${$t('common.selectInfo')}`"
                    >
                        <Option
                            v-for="(item, index) of companyList"
                            :value="item.id"
                            :label="item.name"
                            :key="index"
                        />
                    </Select>
                </FormItem>
                <FormItem :label="$t('安装位置')" prop="orgId">
                    <Cascader
                        :data="orgList"
                        :placeholder="`${$t('common.selectInfo')}`"
                        v-model="formItem.orgId"
                        @on-change="companySelectChange(2)"
                    ></Cascader>
                </FormItem>
                <FormItem :label="$t('maintenance.EquipmentNo')" prop="deviceId">
                    <Select
                        v-model="formItem.deviceId"
                        filterable
                        clearable
                        :placeholder="`${$t('common.selectInfo')}`"
                    >
                        <Option
                            v-for="item of deviceList2"
                            :value="item.id"
                            :key="item.id"
                            :label="item.deviceNo"
                        />
                    </Select>
                </FormItem>
                <FormItem :label="$t('生产节拍')" prop="beat">
                    <Input
                        :placeholder="`${$t('common.inputInfo')}`"
                        type="text"
                        v-model="formItem.beat"
                    ><span slot="append">s</span></Input>
                </FormItem>
            </Form>
            <div slot="footer">
                <Button type="default" @click="addModal = false">{{ $t('common.Cancle') }}</Button>
                <Button type="primary" @click="handleSubmit('formValidate')">{{ $t('maintenance.Confirmed') }}</Button>
            </div>
        </Modal>
        <Modal :mask-closable="false" v-model="deleteModal"  :title="$t('common.Delete')" class="modal-title-layout">
          <div class="icon red">
            <i class="iconfont zy-common-shanchu"></i>
          </div>
          <p class="title">
            <span>{{$t('common.confirmDelete')}}</span>
          </p>
            <div slot="footer">
                <Button type="default" @click="deleteModal = false">{{ $t('common.Cancle') }}</Button>
                <Button type="primary" @click="handleDelete">{{ $t('maintenance.Confirmed') }}</Button>
            </div>
        </Modal>
        <importExcelModal
            :importExcelStateF="importExcelState"
            v-if="importExcelState"
            @importExcelChange="importExcelChange"
        ></importExcelModal>
    </div>
</template>

<script>
import {queryPage} from "@/api/system/production-input/production-interval.js";
import {findOrgByToken, getCompany, selectDeviceList} from "@/api/index.js";
import recursion from "@/util/recursion";
import fileDownload from "js-file-download";
import importExcelModal from "@/components/importExcel.vue";
import toggleTableOperation from "@/mixins/toggleTableOperation";
export default {
    name: "ProductionInterval",
    components: {importExcelModal},
    mixins:[toggleTableOperation],
    data() {
        return {
            searchParams: {},
            columns: [
                {
                    key: "selection",
                    type: "selection",
                    width: 60,
                    align: "center",
                },
                {
                   title: `${ this.$t('common.company') }`,
                    key: 'companyName',
                    align: 'center',
                    resizable: true
                },
                {
                    // title: '安装位置',
                    title: `${ this.$t('安装位置') }`,
                    key: 'orgName',
                    align: 'center',
                    resizable: true
                },
                {
                    title: `${ this.$t('maintenance.EquipmentNo') }`,
                    key: 'deviceNo',
                    align: 'center',
                    resizable: true
                },
                {
                   title: `${ this.$t('maintenance.EquipmentName') }`,
                    key: 'deviceName',
                    align: 'center',
                    resizable: true
                },
                {
                    // title: '生产节拍',
                    title: `${ this.$t('生产节拍') }`,
                    key: 'beat',
                    align: 'center',
                    resizable: true
                },
                {
                    // title: '创建人',
                    title: `${ this.$t('创建人') }`,
                    key: 'createBy',
                    align: 'center',
                    resizable: true
                },
                {
                    // title: '创建时间',
                    title: `${ this.$t('创建时间') }`,
                    key: 'createTime',
                    align: 'center',
                    minWidth: 50,
                    resizable: true
                },
                {
                    title: `${this.$t('common.operation')}`,
                    slot: 'action',
                    align: 'center',
                    fixed:"right",
                    width: 180
                }
            ],
            tableData: [],
            pageSizeOption: [10, 20, 30, 40],
            pageHelper: {
                pageSize: 10,
                pageNum: 1,
                total: 0,
            },
            checkBtnPermission: {},
            orgList: [],
            companyList: [],
            deviceList: [],
            deviceList2: [],
            importExcelState: false,
            deleteIds: [],
            addModal: false,
            formItem: {},
            addtitle: '',
            getRules: {
                belongCompanyId: [
                    {required: true, type: 'number', message: this.$t('common.selectInfo'), trigger: "change"},
                ],
                orgId: [
                    {required: true, type: 'array', message: this.$t('common.selectInfo'), trigger: "change"},
                ],
                deviceId: [
                    {required: true, type: 'number', message: this.$t('common.selectInfo'), trigger: "change"},
                ],
                beat: [
                    {required: true, message: this.$t('common.inputInfo'), trigger: "blur"},
                ]
            },
            deleteModal: false
        }
    },
    created() {
        this.getTableColumnsWidth(this.columns)
    },
    methods: {
        reset (){
            this.searchParams = {};
            this.changeNum();
        },
        changeNum() {
            this.pageHelper.pageNum = 1;
            this.searchList();
        },
        changePageSize(pageSize) {
            this.pageHelper.pageSize = pageSize;
            this.searchList();
        },
        changePageNum(val) {
            this.pageHelper.pageNum = val;
            this.searchList();
        },
        searchList() {//查询列表
            let params = {
                pageNum: this.pageHelper.pageNum,
                pageSize: this.pageHelper.pageSize,
                ...this.searchParams
            };

            queryPage(params).then(res => {
                if (res.code === 200) {
                    this.tableData = res.data.list
                    this.pageHelper.total = res.data.total
                } else {
                    this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                }
            })
        },
        companySelectChange(val) {
            this.getDeviceList(val);
        },
        getOrgList() {
            let params = {
                level: 3
            }
            findOrgByToken(params).then(res => {
                if (res.code === 200) {
                    const obj = {
                        label: 'name',
                        value: 'id',
                        children: 'children'
                    }
                    this.orgList = recursion.convertTree(res.data, obj)
                } else {
                    this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                }
            })
        },
        handleCasChange(val, selectedData) {
            this.searchParams.orgId = val[val.length - 1];
            this.searchParams.orgName = selectedData[selectedData.length - 1].label;
            this.getDeviceList();
        },
        //获取公司
        getCompanyList() {
            getCompany().then(res => {
                if (res.code === 200) {
                    this.companyList = res.data
                } else {
                    this.companyList = []
                    this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                }
            }).finally(() => {
                this.loading = false
            });
        },
        getDeviceList(val = 1) {
          this.deviceList2 = []
          this.deviceList = []
            // setTimeout(() => {
            //
            // }, 10)
          let params = {
            belongCompanyId: val === 1 ? this.searchParams.companyId : this.formItem.belongCompanyId,
            orgId: val === 1 ? this.searchParams.orgId : this.formItem.orgId && this.formItem.orgId.at(-1),
            excludeDeviceId: this.formItem.id
          }
          return selectDeviceList(params).then(res => {
            res.data.forEach(val=>val.id = Number(val.id))
            switch (val) {
              case 1:
                res.data.forEach(item=>this.deviceList.push(item))
                  break;
              case 2:
                res.data.forEach(item=>this.deviceList2.push(item))
                break;
            }
            // this[val === 1 ? 'deviceList' : 'deviceList2'] = res.data;
          }).finally(() => {
            this.loading = false
          });
        },
        onSelectChange(selection) {
            this.deleteIds = selection.map((item) => item.id);
        },
        async showAddModal(row) {
            if (row.id) {
                this.addtitle = `${this.$t('common.Edit')}`
                this.formItem = {
                    belongCompanyId: row.belongCompanyId,
                    orgId: row.orgIds,
                    deviceId: Number(row.deviceId),
                    beat: '' + row.beat,
                    id: row.id
                };
                await this.getDeviceList(2);
            } else {
                this.addtitle = `${this.$t('common.New')}`
                this.formItem = {}
                this.deviceList2 = []
                // this.$refs['formValidate'].resetFields()
            }
          this.addModal = true
        },
        // 新增提交
        handleSubmit(form) {
            this.$refs[form].validate((valid) => {
                if (valid) {
                    const params = {
                        belongCompanyId: this.formItem.belongCompanyId,
                        orgId: this.formItem.orgId.at(-1),
                        deviceId: this.formItem.deviceId,
                        beat: +this.formItem.beat,
                    };
                    if (this.formItem.id) params.id = this.formItem.id;
                    this.axios({
                        method: "post",
                        url: `/dms/interval/${
                            this.formItem.id ? "updateBeat" : "insertBeat"
                        }`,
                        data: params,
                    }).then((res) => {
                        if (res.code === 200) {
                            this.addModal = false;
                            this.changeNum();
                            this.$Message.success(res.msg);
                        } else {
                            this.$Message.warning({
                                content: res.msg,
                                duration: 6,
                                closable: true,
                            });
                        }
                    });
                }
            });
        },
        // 删除操作
        handleDelete() {
            this.axios({
                method: "post",
                url: "/dms/interval/deleteByIds",
                data: {ids: this.deleteIds},
            }).then((res) => {
                if (res.code === 200) {
                    this.deleteModal = false;
                    this.$Message.success(res.msg);
                    this.changeNum();
                    this.deleteIds = []
                } else {
                    this.$Message.warning({
                        content: res.msg,
                        duration: 6,
                        closable: true,
                    });
                }
            });
        },
        // 批量删除
        deleteAll() {
            if (this.deleteIds.length == 0) {
                this.$Message.warning({
                    content:`${ this.$t('common.deleteItems') }`,
                    duration: 6,
                    closable: true,
                });
                return;
            } else {
                this.deleteModal = true;
            }
        },
        //下载模板
        exportTemplate() {
            const filName = `${this.$t('生产节拍')}${this.$t('common.Download')}`;
            this.axios({
                method: "get",
                url: "/dms/interval/downloadTemplate",
                responseType: "blob",
            }).then((res) => {
                fileDownload(res, filName + ".xlsx");
            });
        },
        //导出
        exportTemplateClick() {
            let params = {
                belongCompanyId: this.searchParams.belongCompanyId,
                orgId: this.searchParams.orgId,
                deviceNo: this.searchParams.deviceNo,
                deviceName: this.searchParams.deviceName,
                ids: this.deleteIds,
            };
            const filName = this.$t('生产节拍');
            this.axios({
                method: "post",
                url: "/dms/interval/exportData",
                responseType: "blob",
                data: params,
            }).then((res) => {
                fileDownload(res, filName + ".xlsx");
            });
        },
        /*导入*/
        importExcelShow() {
            this.importExcelState = true;
        },
        importExcelChange(val) {
            this.importExcelState = false;
            if (val === "success") {
                // this.$Message.success("导入成功");
                this.changeNum();
            }
        },
    },

    mounted() {
        this.searchList();
        this.getOrgList();
        this.getCompanyList();
        this.getDeviceList();
    }
}
</script>

<style scoped lang="scss">
.fieldManage {
    .formList {
        padding: 30px;

        .btn {
            margin-top: 20px;
            text-align: center;
            width: 100%;
            height: 40px;
        }

        .inputBorder {
            border: 1px solid #dcdee2;
            border-radius: 4px;
        }
    }
}
</style>

<style lang="scss">

</style>
